package com.zkyc.framework.algorithm.service;

import cn.hutool.extra.tokenizer.Result;
import cn.hutool.extra.tokenizer.TokenizerEngine;
import cn.hutool.extra.tokenizer.Word;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zkyc.framework.common.exception.ResultCode;
import com.zkyc.framework.common.service.RestTemplateService;
import com.zkyc.framework.common.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;

/**
 * @author bing.bai
 * @create 2022/5/17
 */
@Service
@Slf4j
public class SegmentationService {

    @Autowired
    private TokenizerEngine engine;

    @Resource
    RestTemplate restTemplate;


    @Value("${zjlab.chineseCorrect.url}")
    private String chineseCorrectUrl;

    public List<String> chineseSegment(String text) {
        List<String> list = new ArrayList();
        Result result = engine.parse(text);
        while (result.hasNext()) {
            Word next = result.next();
            list.add(next.getText());
        }

        return list;
    }

    public ResultVO chineseCorrect(String para){
        para = Jsoup.clean(para,Whitelist.none());
        if (para.length() > 200){
            para = para.substring(0,200);
        }
        JSONObject requestMap = new JSONObject();
        requestMap.put("text", para);

        //1.请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        //httpHeaders.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE));
        httpHeaders.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        httpHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());

        //2.请求体
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(requestMap, httpHeaders);

        System.out.println(chineseCorrectUrl);
        //使用JSONObject，不需要创建实体类VO来接受返参，缺点是别人不知道里面有哪些字段,即不知道有那些key
        JSONObject body1 = restTemplate.postForObject(chineseCorrectUrl, httpEntity, JSONObject.class);
        log.info("body1:{}",body1);
        return ResultVO.data(body1);

    }


}
